﻿using NetworkLib.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace PBO.Network.Domain
{
    public class BattleTeam : DataByteArray
    {
        public byte position { get; set; }
        public string identity { get; set; }
        public byte[] team { get; set; }

        public override void Read(ByteArray byteArray)
        {
            this.position = byteArray.ReadByte();
            this.identity = byteArray.ReadUTF();
            //this.team = DataByteArray.ReadArray<byte>(byteArray, b => b.ReadByte());

            #region Validate ev & iv

            var array = DataByteArray.ReadArray<byte>(byteArray, b => b.ReadByte());

            var input = new MemoryStream(array);
            var output = new MemoryStream();

            var reader = new BinaryReader(input);
            var writer = new BinaryWriter(output);

            writer.Write(reader.ReadString());
            writer.Write(reader.ReadString());

            for (int i = 0; i < 6; i++)
            {
                int id = reader.ReadInt32();
                if (id == 0) break;
                writer.Write(id);
                writer.Write(reader.ReadString());
                writer.Write(Math.Min((byte)100, reader.ReadByte()));

                byte[] evs = new byte[6];
                for (int j = 0; j < evs.Length; j++)
                {
                    evs[i] = reader.ReadByte();
                }
                if (evs.Cast<int>().Sum() > 510)
                {
                    evs = Enumerable.Repeat<byte>((byte)85, 6).ToArray();
                }
                for (int j = 0; j < evs.Length; j++)
                {
                    writer.Write(evs[i]);
                }

                for (int j = 0; j < 6; j++)
                {
                    writer.Write(Math.Min((byte)31, reader.ReadByte()));
                }

                writer.Write(reader.ReadInt32());
                writer.Write(reader.ReadByte());
                writer.Write(reader.ReadInt32());
                writer.Write(reader.ReadInt32());

                for (int j = 0; j < 4; j++)
                {
                    writer.Write(reader.ReadString());
                }
            }

            reader.Close();
            writer.Close();

            this.team = (byte[])output.GetBuffer().Clone();

            input.Dispose();
            output.Dispose();

            #endregion

        }

        public override void Write(ByteArray byteArray)
        {
            byteArray.WriteByte(this.position);
            byteArray.WriteUTF(this.identity);
            DataByteArray.WriteArray<byte>(this.team, byteArray, (b, t) => b.WriteByte(t));
        }
    }
}
